<!--
 - MineAdmin is committed to providing solutions for quickly building web applications
 - Please view the LICENSE file that was distributed with this source code,
 - For the full copyright and license information.
 - Thank you very much for using MineAdmin.
 -
 - @Author X.Mo<root@imoi.cn>
 - @Link   https://gitee.com/xmo/mineadmin-vue
-->
<template>
  <a-select
  v-model:model-value="value"
  :options="options"
  :multiple="props.component.multiple"
  :size="props.component.size"
  :allow-clear="props.component.allowClear ?? true"
  :disabled="props.component.disabled"
  :readonly="props.component.readonly"
  :error="props.component.error"
  :placeholder="props.component.placeholder ?? `请选择${props.component.title}`"
  :loading="props.component.loading"
  :allow-search="props.component.allowSearch ?? true"
  :allow-create="props.component.allowCreate"
  :max-tag-count="props.component.maxTagCount"
  :bordered="props.component.bordered"
  :unmount-on-close="props.component.unmountOnClose"
  :popup-container="props.component.popupContainer"
  :filter-option="props.component.filterOption"
  :virtual-list-props="props.component.virtualListProps"
  :trigger-props="props.component.triggerProps"
  :format-label="props.component.formatLabel"
  :fallback-option="props.component.fallbackOption"
  :show-extra-options="props.component.showExtraOptions"
  :value-key="props.component.valueKey"
  :search-delay="props.component.searchDelay"
  :limit="props.component.limit"
  :field-names="props.component.fieldNames"
  :scrollbar="props.component.scrollbar"
>
</a-select>
</template>

<script setup>
import {ref, inject, onMounted, nextTick, watch,computed} from 'vue'
import MaFormItem from '@/components/ma-form/formItem/form-item.vue'
import {get, isUndefined, set, xor, isObject, indexOf} from 'lodash'
import {runEvent} from '@/components/ma-form/js/event.js'
import {handlerCascader, loadDict} from '@/components/ma-form/js/networkRequest.js'

const props = defineProps({
  component: Object,
  crudForm: {type: Object},
  serviceIndex: {type: String},
  customField: {type: String},
})

const currentService = computed(() => {
  let serviceDict = props.crudForm?.getColumnService().getDictService('service_id').dictData
  if (!serviceDict) {
    return undefined;
  }
  let currentServiceId = props.crudForm?.getFormData()['service_id']
  let service
  serviceDict.map(i => {
    if (currentServiceId === i.value) {
      service = i.data
    }
  })
  return service
})
const options = computed(() => {
  if (!currentService.value) return [];
  let service_radio = currentService.value[props.serviceIndex].toString();
  if(!service_radio) return props.crudForm?.getColumnService().getDictService(props.component.dataIndex).dictData
  let list = props.crudForm?.getColumnService().getDictService(props.component.dataIndex).dictData.filter(i => {
              return service_radio.indexOf(i.value) !== -1
            })
  return list
})

if (isObject(props.component.dict)) {
  props.component.dict.pageOption = {
    page: 1,
    pageSize: props.component?.dict?.pageSize ?? 10
  }
}

const formModel = inject('formModel')
const dictList = inject('dictList')
const columns = inject('columns')
const getColumnService = inject('getColumnService')
const rv = async (ev, value = undefined) => await runEvent(props.component, ev, {
  formModel,
  getColumnService,
  columns
}, value)

const index = props.customField ?? props.component.dataIndex
const dictIndex = index.match(/^(\w+\.)\d+\./) ? index.match(/^(\w+\.)\d+\./)[1] + props.component.dataIndex : props.component.dataIndex
const value = ref(get(formModel.value, index, ''))
const dataTotal = ref(0)

watch(() => get(formModel.value, index), vl => value.value = vl)
watch(() => value.value, v => {
  set(formModel.value, index, v)
  index.indexOf('.') > -1 && delete formModel.value[index]
})
watch(() => options.value, list => {
  if(list.length === 1){
    value.value=list[0].value
  }else if(!list.map(i=>i.value).includes(value.value)){
    value.value = undefined
  }
})

if (value.value === '') {
  value.value = undefined
} else if (!isUndefined(value.value) && props.component.dict && (props.component.dict.name || props.component.dict.data) && !props.component.multiple) {
  value.value = value.value + ''
}

rv('onCreated')
onMounted(() => {
  setTimeout(() => {
    if (isObject(dictList.value[index])) {
      dataTotal.value = dictList.value[index]?.pageInfo?.total
    }
  }, 800);
  rv('onMounted')
})
</script>
